from sqlalchemy.future import select
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional

from app.models.teacher import Teacher
from app.schemas.teacher import TeacherCreate, TeacherUpdate

async def get_teacher(db: AsyncSession, teacher_id: int) -> Optional[Teacher]:
    result = await db.execute(select(Teacher).filter(Teacher.id == teacher_id))
    return result.scalars().first()

async def get_teacher_by_email(db: AsyncSession, email: str) -> Optional[Teacher]:
    result = await db.execute(select(Teacher).filter(Teacher.email == email))
    return result.scalars().first()

async def get_teachers(db: AsyncSession, skip: int = 0, limit: int = 100) -> List[Teacher]:
    result = await db.execute(select(Teacher).offset(skip).limit(limit))
    return result.scalars().all()

async def create_teacher(db: AsyncSession, teacher: TeacherCreate) -> Teacher:
    db_teacher = Teacher(**teacher.dict())
    db.add(db_teacher)
    await db.commit()
    await db.refresh(db_teacher)
    return db_teacher

async def update_teacher(
    db: AsyncSession, 
    teacher_id: int, 
    teacher_update: TeacherUpdate
) -> Optional[Teacher]:
    result = await db.execute(select(Teacher).filter(Teacher.id == teacher_id))
    db_teacher = result.scalars().first()
    
    if db_teacher:
        update_data = teacher_update.dict(exclude_unset=True)
        for key, value in update_data.items():
            setattr(db_teacher, key, value)
        await db.commit()
        await db.refresh(db_teacher)
    return db_teacher

async def delete_teacher(db: AsyncSession, teacher_id: int) -> Optional[Teacher]:
    result = await db.execute(select(Teacher).filter(Teacher.id == teacher_id))
    db_teacher = result.scalars().first()
    
    if db_teacher:
        await db.delete(db_teacher)
        await db.commit()
    return db_teacher